package com.decent.ejfadmin.utils;

import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.decent.ejfadmin.common.util.OssConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;
import java.util.Date;

/**
 * 阿里云OSS工具类:
 *
 * @author hejl
 * @date 2018/03/26
 */
@Slf4j
public class OSSClientUtil {
    /**
     * endpoint以杭州为例，其它region请按实际情况填写
     */
    private String endpoint = "http://oss-cn-beijing.aliyuncs.com";
    /**
     * accessKey
     */
    private String accessKeyId = "LTAI4G88c17Uc4rrZmGuEDGa";
    private String accessKeySecret = "ac4yF0x2InoECMRk8OdaINfz3z2FV0";
    /**
     * 空间
     */
    private String bucketName = "dlk-shiming";

    private OSSClient ossClient;

    public OSSClientUtil() {
        ossClient = new OSSClient(endpoint, new DefaultCredentialProvider(accessKeyId, accessKeySecret), null);
    }

    /**
     * 初始化
     */
    public void init() {
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }

    /**
     * 销毁
     */
    public void destory() {
        ossClient.shutdown();
    }

    /**
     * 上传图片
     *
     * @param url
     */
    public void uploadImg2Oss(String url, String fileDir) throws Exception {
        File fileOnServer = new File(url);
        FileInputStream fin;
        try {
            fin = new FileInputStream(fileOnServer);
            String[] split = url.split("/");
            this.uploadFile2OSS(fin, split[split.length - 1], fileDir);
        } catch (FileNotFoundException e) {
            throw new Exception("图片上传失败");
        }
    }

    /**
     * 上传图片
     *
     * @param file    图片
     * @param fileDir oss服务器上文件夹
     * @return
     * @throws Exception
     */
    public String uploadImg2Oss(MultipartFile file, String fileDir) throws Exception {
        if (file.getSize() > 1024 * 1024) {
            throw new Exception("上传图片大小不能超过1M！");
        }
        String originalFilename = file.getOriginalFilename();
        try {
            InputStream inputStream = file.getInputStream();
            this.uploadFile2OSS(inputStream, originalFilename, fileDir);
            return originalFilename;
        } catch (Exception e) {
            throw new Exception("图片上传失败");
        }
    }

    /**
     * 上传文件
     *
     * @param file    文件
     * @param fileDir oss服务器上文件夹
     * @return
     * @throws Exception
     */
    public String uploadFileOss(MultipartFile file, String fileDir) throws Exception {
        String originalFilename = file.getOriginalFilename();
        try {
            InputStream inputStream = file.getInputStream();
            this.uploadFile2OSS(inputStream, originalFilename, fileDir);
            return originalFilename;
        } catch (Exception e) {
            throw new Exception("文件上传失败");
        }
    }


    /**
     * 获得图片路径
     *
     * @param fileUrl
     * @return
     */
    public String getImgUrl(String fileUrl, String filedir) {
        if (!StringUtils.isEmpty(fileUrl)) {
            String[] split = fileUrl.split("/");
            return this.getUrl(filedir + split[split.length - 1]);
        }
        return null;
    }

    /**
     * 上传到OSS服务器  如果同名文件会覆盖服务器上的
     *
     * @param instream 文件流
     * @param fileName 文件名称 包括后缀名
     * @return 出错返回"" ,唯一MD5数字签名
     */
    public String uploadFile2OSS(InputStream instream, String fileName, String fileDir) {
        String ret = "";
        try {
            //创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(instream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            //上传文件
            PutObjectResult putResult = ossClient.putObject(bucketName, fileDir + fileName, instream, objectMetadata);
            ret = putResult.getETag();
        } catch (IOException e) {
            log.warn("OSSClientUtils{}", e.getMessage(), e);
        } finally {
            try {
                if (instream != null) {
                    instream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }

    /**
     * Description: 判断OSS服务文件上传时文件的contentType
     *
     * @param filenameExtension 文件后缀
     * @return String
     */
    public static String getcontentType(String filenameExtension) {
        if (OssConstants.BMP.equalsIgnoreCase(filenameExtension)) {
            return OssConstants.IMAGE_BMP;
        }
        if (OssConstants.GIF.equalsIgnoreCase(filenameExtension)) {
            return OssConstants.IMAGE_GIF;
        }
        if (OssConstants.JPEG.equalsIgnoreCase(filenameExtension) ||
                OssConstants.JPG.equalsIgnoreCase(filenameExtension) ||
                OssConstants.PNG.equalsIgnoreCase(filenameExtension)) {
            return OssConstants.IMAGE_JPEG;
        }
        if (OssConstants.HTML.equalsIgnoreCase(filenameExtension)) {
            return OssConstants.TEXT_HTML;
        }
        if (OssConstants.TXT.equalsIgnoreCase(filenameExtension)) {
            return OssConstants.TEXT_PLAIN;
        }
        if (OssConstants.VSD.equalsIgnoreCase(filenameExtension)) {
            return OssConstants.APPLICATION_VND_VISIO;
        }
        if (OssConstants.PPTX.equalsIgnoreCase(filenameExtension) ||
                OssConstants.PPT.equalsIgnoreCase(filenameExtension)) {
            return OssConstants.APPLICATION_VND_MS_POWERPOINT;
        }
        if (OssConstants.DOCX.equalsIgnoreCase(filenameExtension) ||
                OssConstants.DOC.equalsIgnoreCase(filenameExtension)) {
            return OssConstants.APPLICATION_MSWORD;
        }
        if (OssConstants.XML.equalsIgnoreCase(filenameExtension)) {
            return OssConstants.TEXT_XML;
        }
        if (OssConstants.ZIP.equalsIgnoreCase(filenameExtension)
                || OssConstants.EXE.equalsIgnoreCase(filenameExtension)
                || OssConstants.APK.equalsIgnoreCase(filenameExtension)
                || OssConstants.RAR.equalsIgnoreCase(filenameExtension)) {
            return OssConstants.APPLICATION_VND_OCTET_STREAM;
        }
        return OssConstants.IMAGE_JPEG;
    }

    /**
     * 获得url链接
     *
     * @param key
     * @return
     */
    public String getUrl(String key) {
        // 设置URL过期时间为10年  3600l* 1000*24*365*10
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
        // 生成URL
        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
        if (url != null) {
            return url.toString();
        }
        return null;
    }

    /**
     * 通用根据key生成url
     *
     * @param picKey 照片key值
     * @return string
     */
    public String getPicUrl(String picKey) {
        // 过期时间10分钟
        java.sql.Date expiration = new java.sql.Date(System.currentTimeMillis() + 1000 * 60 * 10);
        // 图片处理样式
        GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName, picKey, HttpMethod.GET);
        req.setExpiration(expiration);
        URL signedUrl = ossClient.generatePresignedUrl(req);
        return signedUrl.toString();
    }
}
